package cn.gjxblog.thread.example.sync;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author gjx
 * @version v1.0
 * @Description
 * @date 2019/7/1 14:15
 */
@Slf4j
public class SynchronizedExample1 {

    //修饰代码快，大括号括起来的代码，作用于<调用的对象>
    public void test1(){
        synchronized (this) {
            for (int i = 0; i < 10; i++){
                log.info("test1-{}", i);
            }
        }
    }

    //修饰方法，整个方法，作用于<调用的对象>
    public synchronized  void test2(){
        for (int i = 0; i < 10; i++){
            log.info("test2-{}", i);
        }
    }


    public static void main(String[] args) {
        SynchronizedExample1 example = new SynchronizedExample1();
        SynchronizedExample1 example2 = new SynchronizedExample1();
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(() -> {
            example.test1();
        });
        executorService.execute(() -> {
            example2.test1();
        });
    }
}
